(function(expose){
var g_empty_element_suffix = " />",
    g_tab_width = 4,
    g_str_start_tag = '~~~vespa-str-start-tag~~~',
    g_str_end_tag = '~~~vespa-str-end-tag~~~',
    g_urls = {},
    g_titles = {},
    g_html_blocks = {},
    g_escape_table = {};
    

//Used to track when we're inside an ordered or unordered list
//(see _ProcessListItems() for details):
var g_list_level = 0;
/**
 * 获取全局唯一的占位符
 */
var getUniqueId = (function(){
    var seed = 0;
    return function(){
        seed++;
        return '~~~vespa-'+seed+'~~~';
    }
})();

'`_{}]>#-.!'.split('').forEach(function(value, index){
    g_escape_table[value] = {
        reg : new RegExp(value, 'g'),
        placeholder : getUniqueId()
    };
});

'\\*[()+'.split('').forEach(function(value, index){
    g_escape_table[value] = {
        reg : new RegExp('\\'+value,'g'),
        placeholder : getUniqueId()
    };
});

function createArray(item, len){
    var a = [];
    for(;len>0;len--)
        a.push(item);
        
    return a;
}
/**
 * 获取目标字符串在gbk编码下的字节长度
 */
function getByteLength(source) {
    return String(source).replace(/[^\x00-\xff]/g, "ci").length;
} 
/**
 * Main function. The order in which other subs are called here is
 * essential. Link and image substitutions need to happen before
 * _EscapeSpecialChars(), so that any *'s or _'s in the <a>
 * and <img> tags get encoded.
 */    
function Markdown(text){
    g_urls = {};
    g_titles = {};
    g_html_blocks = {};
    
    //Standardize line endings:
    text = text.replace(/\r\n/g,"\n").replace(/\r/g,"\n");
    
    //Make sure $text ends with a couple of newlines:
    text += "\n\n";
    
    //Convert all tabs to spaces.
    text = _Detab(text);
    // Strip any lines consisting only of spaces and tabs.
    // This makes subsequent regexen easier to write, because we can
    // match consecutive blank lines with /\n+/ instead of something
    // contorted like /[ \t]*\n+/ 
    text = text.replace(
        /^[ \t]+$/gm,
        ""
    );

    // Turn block-level HTML blocks into hash entries
    text = _HashHTMLBlocks(text);
    
    // Strip link definitions, store in hashes.
    text = _StripLinkDefinitions(text);
    
    text = _RunBlockGamut(text);
    
    text = _UnescapeSpecialChars(text);
    
    return text+'\n';
}

/**
 * These are all the transformations that form block-level
 * tags like paragraphs, headers, and list items.
 */
function _RunBlockGamut(text){
    text = _DoHeaders(text);
    //Do Horizontal Rules:
    text = text.replace(
        /^[ ]{0,2}([ ]?\*[ ]?){3,}[ \t]*$/gm,
        '\n<hr'+g_empty_element_suffix+'\n'
    ).replace(
        /^[ ]{0,2}([ ]?-[ ]?){3,}[ \t]*$/gm,
        '\n<hr'+g_empty_element_suffix+'\n'
    ).replace(
        /^[ ]{0,2}([ ]?_[ ]?){3,}[ \t]*$/gm,
        '\n<hr'+g_empty_element_suffix+'\n'
    );

    text = _DoLists(text);
    text = _DoCodeBlocks(text);
    text = _DoBlockQuotes(text);
    /*
    # We already ran _HashHTMLBlocks() before, in Markdown(), but that
	# was to escape raw HTML in the original Markdown source. This time,
	# we're escaping the markup we've just created, so that we don't wrap
	# <p> tags around block-level tags.
	*/
	text = _HashHTMLBlocks(text);
    text = _FormParagraphs(text);
    return text;
}

//	Params:
// text - string to process with html <p> tags
function _FormParagraphs(text){
    // Strip leading and trailing lines:
    text = text
            .replace(/^\n+/,'')
            .replace(/\n+$/,'');

    var grafs = text.split(/\n{2,}/);

    //Wrap <p> tags.
    for(var i=0,len=grafs.length;i<len;i++){
        var item = grafs[i];
        if(!g_html_blocks[item]){
            item = _RunSpanGamut(item);
            item = item.replace(/^([ \t]*)/, '<p>');
            item += "</p>";

            grafs[i] = item;
        }
    }

    //Unhashify HTML blocks
    for(var i=0,len=grafs.length;i<len;i++){
        var item = grafs[i];
        if(g_html_blocks[item]){
            item = g_html_blocks[item];

            grafs[i] = item;
        }
    }

    return grafs.join("\n\n");
}

function _DoBlockQuotes(text){
    text = text.replace(
        new RegExp(
            '('                         //Wrap whole match in $1
			    +'('
			        +'^[ \\t]*>[ \\t]?'   // '>' at the start of a line
			        +'.+\\n'             //rest of the first line
			        +'(.+\\n)*'			// subsequent consecutive lines
			        +'\\n*'              // blanks
			    +')+'
		    +')',

            'gm'
        ),
        function(sMatch, _$1){
            var bq = _$1;
            bq = bq.replace(/^[ \t]*>[ \t]?/gm, '')    // trim one level of quoting
                .replace(/^[ \t]+$/gm, '');              // trim whitespace-only lines
			bq = _RunBlockGamut(bq);		// recurse

			bq = '  '+bq;
			// These leading spaces screw with <pre> content, so we need to fix that:
            bq = bq.replace(
                /(\s*<pre>(?:.|\n)+?<\/pre>)/g,
                function(sMatch, _$1){
                    var pre = _$1;
                    pre = pre.replace(/^  /mg, '');
                    return pre;
                }
            );

			return "<blockquote>\n"+bq+"\n</blockquote>\n\n";
			
        }
    );

    return text;
}

function _DoCodeBlocks(text){
    text = g_str_start_tag + text + g_str_end_tag;
    text = text.replace(
        new RegExp(
            '(?:\\n\\n|'+g_str_start_tag+')'
			+'('	            // $1 = the code block -- one or more lines, starting with a space/tab
                +'(?:'
			        +'(?:[ ]{'+g_tab_width+'}|\\t)'  // Lines must start with a tab or a tab-width of spaces
			        +'.*\\n+'
			    +')+'
			+')'
			+'((?=^[ ]{0,'+g_tab_width+'}\\S)|'+g_str_end_tag+')',	// Lookahead for non-space at line-start, or end of doc

            'gm'
        ),
        function(sMatch, _$1){
            var codeblock = _$1;
			var result; // return value

			codeblock = _EncodeCode(_Outdent(codeblock));
			codeblock = _Detab(codeblock);
            codeblock = codeblock.replace(
                new RegExp('^'+g_str_start_tag+'\\n+'), ''  // trim leading newlines
            ).replace(
                new RegExp('\\s+'+g_str_end_tag+'$'), ''    // trim trailing whitespace
            );

			result = "\n\n<pre><code>" + codeblock + "\n</code></pre>\n\n";

			return result;
        }
    );
    text = text.replace(new RegExp('^'+g_str_start_tag), '').replace(new RegExp(g_str_end_tag+'$'), '');
    return text;
}

//Form HTML ordered (numbered) and unordered (bulleted) lists.
function _DoLists(text){
    var less_than_tab = g_tab_width - 1;
    //Re-usable patterns to match list item bullets and number markers:
    var marker_ul  = '[*+-]',
        marker_ol  = '\\d+[.]',
        marker_any = '(?:'+marker_ul+'|'+marker_ol+')';
    //Re-usable pattern to match any entirel ul or ol list:
    var whole_list = 
        '('                               //$1 = whole list
          +'('                            // $2
            +'[ ]{0,'+less_than_tab+'}'
            +'('+marker_any+')'            // $3 = first list item marker
            +'[ \\t]+'
          +')'
          +'((?:.|\\n)+?)'
          +'('
            +'(?='+g_str_end_tag+')'
            +'|'
            +'\\n{2,}'
            +'(?=\\S)'
            +'(?!'                       // Negative lookahead for another list item marker
              +'[ \\t]*'
              +marker_any+'[ \\t]+'
            +')'
          +')'
        +')';
    
    /*
     * # We use a different prefix before nested lists than top-level lists.
    # See extended comment in _ProcessListItems().
    #
    # Note: There's a bit of duplication here. My original implementation
    # created a scalar regex pattern as the conditional result of the test on
    # $g_list_level, and then only ran the $text =~ s{...}{...}egmx
    # substitution once, using the scalar as the pattern. This worked,
    # everywhere except when running under MT on my hosting account at Pair
    # Networks. There, this caused all rebuilds to be killed by the reaper (or
    # perhaps they crashed, but that seems incredibly unlikely given that the
    # same script on the same server ran fine *except* under MT. I've spent
    # more time trying to figure out why this is happening than I'd like to
    # admit. My only guess, backed up by the fact that this workaround works,
    # is that Perl optimizes the substition when it can figure out that the
    # pattern will never change, and when this optimization isn't on, we run
    # afoul of the reaper. Thus, the slightly redundant code to that uses two
    # static s/// patterns rather than one conditional pattern.
     */


    if (g_list_level) {
        text += g_str_end_tag;
        text = text.replace(
            new RegExp(
                '^' + whole_list,
                'gm'
            ),function(sMatch, _$1, _$2, _$3){
                var list = _$1,
                    type_reg = new RegExp(marker_ul),
                    list_type = (type_reg.test(_$3)) ? 'ul' : 'ol';
                //Turn double returns into triple returns, so that we can make a
                // paragraph for the last item in a list, if necessary:
                list = list.replace(/\n{2,}/g, '\n\n\n');
                var result = _ProcessListItems(list, marker_any);
                result = "<"+list_type+">\n" + result + "</"+ list_type +">\n";
                return result;
            }
        );
        text = text.replace(new RegExp(g_str_end_tag+'$'), '');
    }else{
        text = g_str_start_tag + text + g_str_end_tag;
        text = text.replace(
            new RegExp(
                '(\\n\\n|'+g_str_start_tag+'\\n?)' + whole_list,
                'gm'
            ),function(sMatch, _$1, _$2, _$3, _$4){
                var list = _$2,
                    type_reg = new RegExp(marker_ul),
                    list_type = (type_reg.test(_$4)) ? 'ul' : 'ol';
                //Turn double returns into triple returns, so that we can make a
                // paragraph for the last item in a list, if necessary:
                list = list.replace(/\n{2,}/g, '\n\n\n');
                var result = _ProcessListItems(list, marker_any);
                result = "<"+list_type+">\n" + result + "</"+ list_type +">\n";
                return _$1 + result;
            }
        );
        text = text.replace(new RegExp('^'+g_str_start_tag), '').replace(new RegExp(g_str_end_tag+'$'), '');
    }

    return text;
    
}

//Process the contents of a single ordered or unordered list, splitting it
//into individual list items.
function _ProcessListItems(list_str, marker_any){
    /*
     * # The $g_list_level global keeps track of when we're inside a list.
    # Each time we enter a list, we increment it; when we leave a list,
    # we decrement. If it's zero, we're not in a list anymore.
    #
    # We do this because when we're not inside a list, we want to treat
    # something like this:
    #
    #       I recommend upgrading to version
    #       8. Oops, now this line is treated
    #       as a sub-list.
    #
    # As a single paragraph, despite the fact that the second line starts
    # with a digit-period-space sequence.
    #
    # Whereas when we're inside a list (or sub-list), that line will be
    # treated as the start of a sub-list. What a kludge, huh? This is
    # an aspect of Markdown's syntax that's hard to parse perfectly
    # without resorting to mind-reading. Perhaps the solution is to
    # change the syntax rules such that sub-lists must start with a
    # starting cardinal number; e.g. "1." or "a.".
     */
    g_list_level++;

    list_str = list_str.replace(/\n{2,}$/,'\n');
    list_str += g_str_end_tag;
    
    list_str = list_str.replace(
        new RegExp(
            '(\\n)?'                           // leading line = $1
            + '(^[ \\t]*)'                       // leading whitespace = $2
            + '('+marker_any+')[ \\t]+'            // list marker = $3
            + '(((?:.|\\n)+?)'                       // list item text   = $4
            + '(\\n{1,2}))'
            + '(?=\\n*('+g_str_end_tag+'|\\2('+marker_any+')[ \\t]+))',
            
            'gm'
        ),function(sMatch, _$1, _$2, _$3, _$4){
            var item = _$4,
                leading_line = _$1,
                leading_space = _$2;
                
            if(leading_line || /\n{2,}/.test(item)){
                item = _RunBlockGamut(_Outdent(item));
            }else{
                //Recursion for sub-lists:
                item = _DoLists(_Outdent(item));
                item = item.replace(/\n$/, '');
                item = _RunSpanGamut(item);
                
            }
            return '<li>'+item+'</li>\n';
        }
    );
    list_str = list_str.replace(new RegExp(g_str_end_tag+'$'), '');
    g_list_level--;
    return list_str;
}

//Remove one level of line-leading tabs or spaces
function _Outdent(text){
    return text.replace(
        new RegExp(
            '^(\\t|[ ]{1,'+g_tab_width+'})',
            'gm'
        ),
        
        ''
    );
}


function _DoHeaders(text){
    /**
     * Setext-style headers:
     *     Header 1
     *     ========
     *  
     *     Header 2
     *     --------
     */
    text = text.replace(
        /^(.+)[ \t]*\n=+[ \t]*\n+/gm,
        function(sMatch, _$1){
            return "<h1>" + _RunSpanGamut(_$1) + "</h1>\n\n";
        }
    ).replace(
        /^(.+)[ \t]*\n-+[ \t]*\n+/gm,
        function(sMatch, _$1){
            return "<h2>"+_RunSpanGamut(_$1)+"</h2>\n\n";
        }
    );
    
    /* # atx-style headers:
    #   # Header 1
    #   ## Header 2
    #   ## Header 2 with closing hashes ##
    #   ...
    #   ###### Header 6
     */
    text = text.replace(
        new RegExp(
            '^(\\#{1,6})'  //$1 = string of #'s
            +'[ \\t]*'
            +'(.+?)'       //$2 = Header text
            +'[ \\t]*'
            +'\\#*'         //optional closing #'s (not counted)
            +'\\n+',
            
            'gm'
        ),function(sMatch, _$1, _$2){
            var h_level = _$1.length;
            return "<h"+h_level+">" + _RunSpanGamut(_$2) + "</h"+h_level+">\n\n";
        }
    );
    
    return text;
}

/**
 * These are all the transformations that occur *within* block-level
 * tags like paragraphs, headers, and list items.
 */
function _RunSpanGamut(text){
    text = _DoCodeSpans(text);
    text = _EscapeSpecialChars(text);
    
    /*
     * # Process anchor and image tags. Images must come first,
    # because ![foo][f] looks like an anchor.
     */
    text = _DoImages(text);
    text = _DoAnchors(text);
    
    // Make links out of things like `<http://example.com/>`
    // Must come after _DoAnchors(), because you can use < and >
    // delimiters in inline links like [this](<url>).
    text = _DoAutoLinks(text);
    text = _EncodeAmpsAndAngles(text);
    text = _DoItalicsAndBold(text);
    text = text.replace(/ {2,}\n/g,'<br'+ g_empty_element_suffix+'\n');
    return text;
}

function _DoItalicsAndBold(text){
    text = text.replace(
        /(\*\*|__)(?=\S)(.*?\S)\1/g,
        function(sMatch, _$1, _$2){
            return '<strong>'+_$2+'</strong>';
        }
    );
    
    text = text.replace(
        /(\*|_)(?=\S)(.*?\S)\1/g,
        function(sMatch, _$1, _$2){
            return '<em>'+_$2+'</em>';
        }
    );
    
    return text;
}

function _DoAutoLinks(text){
    text = text.replace(/<((https?|ftp):[^'">\s]+)>/gi, 
        function(sMatch, _$1){
            return '<a href="'+_$1+'">'+_$1+'</a>';
        }
    );
    
    //Email addresses: <address@domain.foo>
    text = text.replace(
        new RegExp(
            '<'
            +'(?:mailto:)?'
            +'('
                +'[-.\\w]+'
                +'\\@'
                +'[-a-z0-9]+(\\.[-a-z0-9]+)*\\.[a-z]+'
            +')'
            +'>',
            
            'gi'
        ),function(sMatch, _$1){
            return _EncodeEmailAddress(_UnescapeSpecialChars(_$1));
        }
    );
    
    return text;
}

function _EncodeEmailAddress(addr){
    /**
     * #    Input: an email address, e.g. "foo@example.com"
#
#   Output: the email address as a mailto link, with each character
#       of the address encoded as either a decimal or hex entity, in
#       the hopes of foiling most address harvesting spam bots. E.g.:
#
#     <a href="&#x6D;&#97;&#105;&#108;&#x74;&#111;:&#102;&#111;&#111;&#64;&#101;
#       x&#x61;&#109;&#x70;&#108;&#x65;&#x2E;&#99;&#111;&#109;">&#102;&#111;&#111;
#       &#64;&#101;x&#x61;&#109;&#x70;&#108;&#x65;&#x2E;&#99;&#111;&#109;</a>
#
#   Based on a filter by Matthew Wickline, posted to the BBEdit-Talk
#   mailing list: <http://tinyurl.com/yu7ue>
     */
    addr = "mailto:"+addr;
    var newStr = '';
    for(var i=0, len=addr.length;i<len;i++){
        if(addr[i] != ":")
            newStr += '&#' + addr.charCodeAt(i) + ';';
        else
            newStr += ":";
    }
    
    addr = '<a href="'+ newStr +'">'+ newStr +'</a>';
    addr = addr.replace(/">.+?:/, '">'); //strip the mailto: from the visible part
    return addr;
}

//Swap back in all the special characters we've hidden.
function _UnescapeSpecialChars(text){
    for(var i in g_escape_table){
        text = text.replace(
            new RegExp(
                g_escape_table[i].placeholder,
                'g'
            ),i
        );
        
    }
    return text;
}

/**
 * Turn Markdown link shortcuts into XHTML <a> tags.
 */
function _DoAnchors(text){
    //First, handle reference-style links: [link text] [id]
    text = text.replace(
        new RegExp(
            '('                   //wrap whole match in $1
              +'\\['
                +'((?:.|\\n)*?)'    //link text = $2
              +'\\]'
    
              +'[ ]?'              //one optional space
              +'(?:\\n[ ]*)?'       //one optional newline followed by spaces
    
              +'\\['
                +'((?:.|\\n)*?)'       // id = $3
              +'\\]'
            +')',
            
            'g'
        ),function(sMatch, _$1, _$2, _$3){
            var result,
                whole_match = _$1,
                link_text    = _$2,
                link_id     = _$3.toLowerCase();

            if (link_id == "") {
                link_id = link_text.toLowerCase();     // for shortcut links like ![this][].
            }
            if(g_urls[link_id]){
                var url = g_urls[link_id];
                url = url.replace(/\*/g, g_escape_table['*'].placeholder)   //We've got to encode these to avoid
                         .replace(/_/g, g_escape_table['_'].placeholder);   //conflicting with italics/bold.
                result = '<a href="'+url+'"';
                if(g_titles[link_id]){
                    title = g_titles[link_id];
                    title = title.replace(/\*/g, g_escape_table['*'].placeholder).replace(/_/g, g_escape_table['_'].placeholder);
                    result += ' title="'+title+'"';
                }
                result += '>'+link_text+'</a>';
            }else{
                result = whole_match;
            }
            return result;
        }
    );
    
    //Next, inline-style links: [link text](url "optional title")
    text = text.replace(
        new RegExp(
            '('               // wrap whole match in $1
              +'\\['
                +'((?:.|\\n)*?)'    //link text = $2
              +'\\]'
              +'\\('            //literal paren
                +'[ \\t]*'
                +'<?((?:.|\\n)*?)>?'   //href = $3
                +'[ \\t]*'
                +'(?:'           //$4
                  +'(?:[\'"])'    //quote char = $5
                  +'((?:.|\\n)*?)'     //Title = $6
                  +'\\5'        //matching quote
                +')?'          //title is optional
              +'\\)'
            +')',
            
            'g'
        ),function(sMatch, _$1, _$2, _$3, _$4){
            var result,
                whole_match = _$1,
                link_text = _$2,
                url = _$3,
                title = _$4;

            url = url.replace(/\*/g, g_escape_table['*'].placeholder).replace(/_/g, g_escape_table['_'].placeholder);
            result = "<a href=\""+url+"\"";
            if(title){
                title = text
                    .replace(/"/g, "&quot;")
                    .replace(/\*/g, g_escape_table['*'].placeholder)
                    .replace(/_/g, g_escape_table['_'].placeholder);
                    
                result +=  " title=\""+title+"\"";
            }
            result += ">"+link_text+"</a>";
            return result;
        }
    );
    
    return text;
}

/**
 * Turn Markdown image shortcuts into <img> tags.
 */
function _DoImages(text){
    //First, handle reference-style labeled images: ![alt text][id]
    text = text.replace(
        new RegExp(
            '('                     //wrap whole match in $1
                +'!\\['
                +'((?:.|\\n)*?)'            //alt text = $2
                +'\\]'
                +'[ ]?'             //one optional space
                +'(?:\\n[ ]*)?'     //one optional newline followed by spaces
                +'\\['
                    +'((?:.|\\n)*?)'        //id = $3
                +'\\]'
            +')',
            
            'g'
        ),function(sMatch, _$1, _$2, _$3){
            var result,
                whole_match = _$1,
                alt_text    = _$2,
                link_id     = _$3.toLowerCase();
                
            if(link_id == ''){
                link_id = alt_text.toLowerCase();
            }
            
            alt_text = alt_text.replace(/"/g,"&quot;");
            if(g_urls[link_id]){
                var url = g_urls[link_id];
                url = url.replace(/\*/g, g_escape_table['*'].placeholder)   //We've got to encode these to avoid
                         .replace(/_/g, g_escape_table['_'].placeholder);   //conflicting with italics/bold.
                result = '<img src="'+url+'" alt="'+alt_text+'"';
                if(g_titles[link_id]){
                    var title = g_titles[link_id];
                    title = title.replace(/\*/g, g_escape_table['*'].placeholder).replace(/_/g, g_escape_table['_'].placeholder);
                    result += ' title="'+title+'"';
                }
                result += g_empty_element_suffix;
            }else{
                //If there's no such link ID, leave intact:
                result = whole_match;
            }
            
            return result;
        }
    );
    
    //Next, handle inline images:  ![alt text](url "optional title")
    //Don't forget: encode * and _
    text = text.replace(
        new RegExp(
            '('               // wrap whole match in $1
              +'!\\['
                +'((?:.|\\n)*?)'       // alt text = $2
              +'\\]'
              +'\\('           // literal paren
                +'[ \\t]*'
                +'<?(\\S+?)>?' // src url = $3
                +'[ \\t]*'
                +'('           // $4
                  +'([\'"])'    // quote char = $5
                  +'((?:.|\\n)*?)'     // title = $6
                  +'\5'        // matching quote
                  +'[ \\t]*'
                +')?'          // title is optional
              +'\\)'
            +')',
            
            'g'
        ),function(sMatch, _$1, _$2, _$3, _$4, _$5, _$6){
            var result,
                whole_match = _$1,
                alt_text = _$2,
                url = _$3,
                title = '';
            if(_$6)
                title = _$6;
                
            alt_text = alt_text.replace(/"/g, "&quot;");
            title = title.replace(/"/g, "&quot;");
            url = url.replace(/\*/g, g_escape_table['*'].placeholder)   //We've got to encode these to avoid
                     .replace(/_/g, g_escape_table['_'].placeholder);   //conflicting with italics/bold.
            result = '<img src="'+url+'" alt="'+alt_text+'"';
            if(title){
                title = text.replace(/\*/g, g_escape_table['*'].placeholder).replace(/_/g, g_escape_table['_'].placeholder);
                result += ' title="'+title+'"';
            }
            result += g_empty_element_suffix;
            return result;
        }
    );
    return text;
}

function _EscapeSpecialChars(text){
    var tokens = _TokenizeHTML(text),
        str = '';
        
    for(var i=0, len=tokens.length;i<len;i++){
        var cur_token = tokens[i];
        if('tag' == cur_token[0]){
            /*
            # Within tags, encode * and _ so they don't conflict
            # with their use in Markdown for italics and strong.
            # We're replacing each such character with its
            # corresponding MD5 checksum value; this is likely
            # overkill, but it should prevent us from colliding
            # with the escape values by accident.
            */
           cur_token[1] = cur_token[1].replace(/\*/g, g_escape_table['*'].placeholder);
           cur_token[1] = cur_token[1].replace(/_/g, g_escape_table['_'].placeholder);
           str += cur_token[1];
        }else{
            str += _EncodeBackslashEscapes(cur_token[1]);
        }
    }
    
    return str;
}

/*
#   Parameter:  String.
#   Returns:    The string, with after processing the following backslash
#               escape sequences.
 */
function _EncodeBackslashEscapes(text){
    return text
            .replace(/\\\\/g, g_escape_table['\\'].placeholder)
            .replace(/\\`/g, g_escape_table['`'].placeholder)
            .replace(/\\\*/g, g_escape_table['*'].placeholder)
            .replace(/\\_/g, g_escape_table['_'].placeholder)
            .replace(/\\\{/g, g_escape_table['{'].placeholder)
            .replace(/\\\}/g, g_escape_table['}'].placeholder)
            .replace(/\\\[/g, g_escape_table['['].placeholder)
            .replace(/\\\]/g, g_escape_table[']'].placeholder)
            .replace(/\\\(/g, g_escape_table['('].placeholder)
            .replace(/\\\)/g, g_escape_table[')'].placeholder)
            .replace(/\\>/g, g_escape_table['>'].placeholder)
            .replace(/\\\#/g, g_escape_table['#'].placeholder)
            .replace(/\\\+/g, g_escape_table['+'].placeholder)
            .replace(/\\\-/g, g_escape_table['-'].placeholder)
            .replace(/\\\./g, g_escape_table['.'].placeholder)
            .replace(/\\!/g, g_escape_table['!'].placeholder);
}

/**
#   Parameter:  String containing HTML markup.
#   Returns:    Reference to an array of the tokens comprising the input
#               string. Each token is either a tag (possibly with nested,
#               tags contained therein, such as <a href="<MTFoo>">, or a
#               run of text between tags. Each element of the array is a
#               two-element array; the first is either 'tag' or 'text';
#               the second is the actual value.
#
#
#   Derived from the _tokenize() subroutine from Brad Choate's MTRegex plugin.
#       <http://www.bradchoate.com/past/mtregex.php>
 */
function _TokenizeHTML(str){
    var pos = 0,
        len = str.length,
        tokens = [],
        depth = 6,
        nested_tags = '',
        match = '';
        
    nested_tags = createArray('(?:<[a-z/!$](?:[^<>]', depth).join('|') + createArray(')*>)', depth).join('');
    match = '(?:<!(?:--(?:.|\\n)*?--\\s*)+>)|'  //comment
        + '(?:<\\?(?:.|\\n)*?\\?>)|'           //processing
        + nested_tags;                  //nested tags
    
    str.replace(
        new RegExp(
            '(' + match + ')',
            'gi'
        ),
        function(sMatch, _$1, _start){
            var whole_tag = _$1,
                tag_start = _start;
            if(pos < tag_start){
                tokens.push(['text',str.substr(pos,tag_start-pos)]);
            }
            tokens.push(['tag', whole_tag]);
            pos = tag_start + whole_tag.length;
        }
    );
    if(pos<len){
        tokens.push(['text',str.substr(pos,len-pos)]);
    }
    
    return tokens;
}

/**
 *   *   Backtick quotes are used for <code></code> spans.
 * 
 *   *   You can use multiple backticks as the delimiters if you want to
 *       include literal backticks in the code span. So, this input:
 *     
 *         Just type ``foo `bar` baz`` at the prompt.
 *     
 *       Will translate to:
 *     
 *         <p>Just type <code>foo `bar` baz</code> at the prompt.</p>
 *     
 *       There's no arbitrary limit to the number of backticks you
 *       can use as delimters. If you need three consecutive backticks
 *       in your code, use four for delimiters, etc.
 *
 *   *   You can use spaces to get literal backticks at the edges:
 *     
 *         ... type `` `bar` `` ...
 *     
 *       Turns to:
 *     
 *         ... type <code>`bar`</code> ...
 */
function _DoCodeSpans(text){
    text = text.replace(
        new RegExp(
            '(`+)'          //$1 = Opening run of `
            + '((.|\\n)+?)'  //$2 = The code block
            + '\\1'          //Matching closer
            + '(?!`)',
            
            'g'
        ),
        function(sMatch, _$1, _$2){
            var s = _$2.replace(/^[ \t]*/g, '');    //leading whitespace
            s = s.replace(/[ \t]*$/g, '');          //trailing whitespace
            s = _EncodeCode(s);
            return "<code>"+s+"</code>";
        }
    );
    
    return text;
}


/**
 * Encode/escape certain characters inside Markdown code runs.
 * The point is that in code, these characters are literals,
 * and lose their special Markdown meanings.
 */
function _EncodeCode(text){
    // Encode all ampersands; HTML entities are not
    // entities within a Markdown code span.
    text = text.replace(/&/g, '&amp;');
    
    // Do the angle bracket song and dance:
    text = text.replace(/</g, '&lt;').replace(/>/g, '&gt;');
    
    // Now, escape characters that are magic in Markdown:
    //why not use /([\*_\{\}\[\]\\])/g? because the thime it excute;
    text = text.replace(/\*/g, g_escape_table['*'].placeholder)
                .replace(/_/g, g_escape_table['_'].placeholder)
                .replace(/\{/g, g_escape_table['{'].placeholder)
                .replace(/\}/g, g_escape_table['}'].placeholder)
                .replace(/\[/g, g_escape_table['['].placeholder)
                .replace(/\]/g, g_escape_table[']'].placeholder)
                .replace(/\\/g, g_escape_table['\\'].placeholder);
    return text;
}

/**
 * Strips link definitions from text, stores the URLs and titles in
 * hash references.
 */
function _StripLinkDefinitions(text){
    var less_than_tab = g_tab_width - 1;
    
    // Link defs are in the form: ^[id]: url "optional title"
    text = text.replace(
        new RegExp(
            '^[ ]{0,'+less_than_tab+'}\\[(.+)\\]:'  //id = $1
            + '[ \\t]*'
            + '\\n?'                                //maybe *one* newline
            + '[ \\t]*'
            + '<?(\\S+?)>?'                         //url = $2
            + '[ \\t]+'
            + '\\n?'                                //maybe one newline
            + '[ \\t]*'
            + '(?:'
            +   '["|\\(]'
            +   '(.+?)'                             //title = $3
            +   '["|\\)]'
            +   '[ \\t]*'
            + ')?'                                  //title is optional
            + '(?:\\n+)',
            
            'gm'
        ),function(sMatch, _$1, _$2, _$3){
            
            g_urls[_$1.toLowerCase()] = _EncodeAmpsAndAngles( _$2 ); // Link IDs are case-insensitive
            if(_$3){
                g_titles[_$1.toLowerCase()] = _$3.replace(/"/g, "&quot;");
            }

            return '';
        }
    );
    
    return text;
}

/**
 * Smart processing for ampersands and angle brackets that need to be encoded.
 */
function _EncodeAmpsAndAngles(text){
    // Ampersand-encoding based entirely on Nat Irons's Amputator MT plugin:
    //   http://bumppo.net/projects/amputator/
    text = text.replace(/&(?!#?[xX]?(?:[0-9a-fA-F]+|\w+);)/g, '&amp;');
    
    // Encode naked <'s
    text = text.replace(/<(?![a-z\/\?\$!])/gi, '&lt;');
    
    return text;
}

/**
 * Hashify HTML blocks:
 * We only want to do this for block-level HTML tags, such as headers,
 * lists, and tables. That's because we still want to wrap <p>s around
 * "paragraphs" that are wrapped in non-block-level tags, such as anchors,
 * phrase emphasis, and spans. The list of tags we're looking for is
 */
function _HashHTMLBlocks(text){
    var less_than_tab = g_tab_width - 1;
    // hard-coded:
    var block_tags_a = 'p|div|h[1-6]|blockquote|pre|table|dl|ol|ul|script|noscript|form|fieldset|iframe|math|ins|del',
        block_tags_b = 'p|div|h[1-6]|blockquote|pre|table|dl|ol|ul|script|noscript|form|fieldset|iframe|math';
    
    /* First, look for nested blocks, e.g.:
       <div>
           <div>
           tags for inner block must be indented.
           </div>
       </div>
    
     The outermost tags must start at the left margin for this to match, and
     the inner nested divs must be indented.
     We need to do this before the next, more liberal match, because the next
     match will start at the first `<div>` and stop at the first `</div>`.
    */
   text = text.replace(
       new RegExp(
           '('                      //save in $1
           + '^'                    //start of line
           + '<('+block_tags_a+')'  //start tag = $2
           + '\\b'                  //word break
           + '(.*\\n)*?'            //any number of lines, minimally matching
           + '</\\2>'               //the matching end tag
           + '[ \\t]*'              //trailing spaces/tabs
           + '(?=\\n+)'             //followed by a newline
           + ')',
           
           'gm'
       ),
       function(sMatch,_$1){
           var key = getUniqueId();
           g_html_blocks[key] = _$1;
           return '\n\n' + key + '\n\n';
       }
   );
   

    //Now match more liberally, simply from `\n<tag>` to `</tag>\n`
    text = text.replace(
       new RegExp(
           '('                      //save in $1
           + '^'                    //start of line
           + '<('+block_tags_b+')'  //start tag = $2
           + '\\b'                  //word break
           + '(.*\\n)*?'            //any number of lines, minimally matching
           + '.*</\\2>'             //the matching end tag
           + '[ \\t]*'              //trailing spaces/tabs
           + '(?=\\n+)'             //followed by a newline
           + ')',
           
           'gm'
       ),
       function(sMatch,_$1){
           var key = getUniqueId();
           g_html_blocks[key] = _$1;
           return '\n\n' + key + '\n\n';
       }
   );
   
   //Special case just for <hr />. It was easier to make a special case than
   //to make the other regex more complicated.
   text = text.replace(
       new RegExp(
           '\\n\\n'         //starting after a blank line
           + '('            //save in $1
           + '[ ]{0,'+less_than_tab+'}'
           + '<(hr)'        // start tag = $2
           + '\\b'          //work break
           + '[^<>]*?'
           + '/?>'          //the matching end tag
           + '[ \\t]*'
           + '(?=\\n{2,})'  //followed by a blank line or end of document
           + ')',
           
           'g'
       ),
       function(sMatch, _$1){
           var key = getUniqueId();
           g_html_blocks[key] = _$1;
           return '\n\n'    //vespa: To keep the same with markdown.pl, add the line that we matched in the begine
                    + '\n\n'+key+'\n\n';
       }
   );
   
   //Special case for standalone HTML comments:
   text = text.replace(
       new RegExp(
           '\\n\\n'                         //starting after a blank line
           + '('                            //save in $1
           +    '[ ]{0,'+less_than_tab+'}'
           +    '('
           +        '<!--(.|\\n)*?--\\s*>'
           +    ')'
           +    '[ \\t]*'
           +    '(?=\\n{2,})'               //followed by a blank line or end of document
           + ')',
           
           'g'
       ),
       function(sMatch, _$1){
           var key = getUniqueId();
           g_html_blocks[key] = _$1;
           return '\n\n'    //vespa: To keep the same with markdown.pl, add the line that we matched in the begine
                    + '\n\n'+key+'\n\n';
       }
   );
   
   return text;
}

function _Detab(text){
    text = text.replace(
        /(.*?)\t/g,
        function(sMatch, _$1){
            return _$1 + (new Array(g_tab_width - getByteLength(_$1)%g_tab_width+1)).join(" ");
        }
    );
    return text;
}
    
expose.toHTML = Markdown;
expose._TokenizeHTML = _TokenizeHTML;
})(Vpa.Markdown);
